﻿using System;
using System.Collections.Generic;
using System.Linq;
using EntityFrameworkExtension.Interface;

namespace EntityFrameworkExtension.Caching
{
    /// <summary>
    /// Simple class to encapsulate the caching of a simple list of data
    /// </summary>
    public class CacheableListOfData<T> where T : class, IEquatable<T>
    {

        private readonly object lockObj;
        private List<T> data;
        private readonly Func<IEfContext, List<T>> functionToGetData;

        public CacheableListOfData(Func<IEfContext, List<T>> functionToGetData)
        {
            lockObj = new object();
            this.functionToGetData = functionToGetData;
        }

        public void ReloadData(IEfContext dataaccess)
        {
            lock (lockObj)
                data = functionToGetData(dataaccess);
        }

        public List<T> GetData(IEfContext dataaccess)
        {
            if (data == null)
                ReloadData(dataaccess);
            return data;
        }


        public void UpdateData(IEqualityComparer<T> comparer, IEfContext dataAccess)
        {
            lock (lockObj)
            {
                if (data == null)
                    data = new List<T>();

                data = functionToGetData(dataAccess).Union(data, comparer).ToList();
            }
        }



        public void AddToCache(T item)
        {
            if (data == null)
                data = new List<T>();

            lock (lockObj)
            {
                if (data.Contains(item))
                    return;

                data.Add(item);
            }
        }
    }
}
